import Vue from 'vue'
import VueRouter from 'vue-router'
import DefaultLayout from '@/layout/defaultLayout/index'
import yunPacs from './modules/yunPacs'
import store from '../store/index'
import { MessageBox, Message } from 'element-ui'
import Mgr from '@/utils/SecurityService'
import { getUserInfo } from '@/api/commonHttp'

// 连续点击路由报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

/**
 * 路由相关属性说明
 * hidden: 当设置hidden为true时，意思不在sideBars侧边栏中显示
 * mete{
 * title: xxx,  设置sideBars侧边栏名称
 * icon: xxx,  设置ideBars侧边栏图标
 * noCache: true  当设置为true时不缓存该路由页面
 * }
 */
const baseUrl = process.env.NODE_ENV === 'development' ? '' : '/paservice'
export const currencyRoutes = [
  {
    path: baseUrl + '/',
    component: DefaultLayout,
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import(/* webpackChunkName: "about" */ '@/views/home'),
        meta: { title: '首页', icon: 'el-icon-s-data' }
      }
    ]
    // redirect: '/about',
    // children: [
    //   {
    //     path: 'about',
    //     name: 'About',
    //     component: () => import(/* webpackChunkName: "about" */ '@/views/about.vue'),
    //     meta: { title: '首页', icon: 'el-icon-s-data' }
    //   }
    // ]
  },
  ...yunPacs
]
let router = {}
function setRouterConfig () {
  const creatRouter = () => {
    //  base地址判断
    let base = '/'
    if (window.Config.subdir != '') {
      base = window.Config.subdir
    }
    return new VueRouter({
      mode: 'history',
      base: base,
      routes: currencyRoutes,
      scrollBehavior () {
        return { x: 0, y: 0 }
      }
    })
  }

  router = creatRouter()
  
  // 导航守卫
  router.beforeEach(async (to, from, next) => {

    if (to.path === '/login') {
      next()
    } else {

      // 动态设置title
      const portalsInfo = localStorage.getItem('portalsInfo') ? JSON.parse(localStorage.getItem('portalsInfo')) : ''
      document.title = portalsInfo && portalsInfo.name ? portalsInfo.name : (to.meta.title || '医网云-影像存档')
      // 第一次进入系统
      if(store.getters.firstEnter) {
        if(to.query.group === 'tenancy') {
          store.commit('permission/SET_GROUP', 'tenancy')
        }else if(to.query.group === 'dept') {
          store.commit('permission/SET_GROUP', 'dept')
        }else if(to.query.group === 'doct') {
          store.commit('permission/SET_GROUP', 'doct')
        }
        if(to.query.systemid) {
          store.commit('permission/SET_SYSTEMID', to.query.systemid)
          console.log('保存过systemid',to.query.systemid);
        }
        if(to.query.scope && to.query.scope === 'institution' && to.query.systemid) {
          store.commit('permission/SET_SCOPE', to.query.scope)
          let res = JSON.parse(store.getters.loginInfo);
          if (!res) {
            const manager = new Mgr();
            res = await manager.getRole()
          }
          if(res) {
            console.log('manager.getRole()获取到的数据',res);
            store.commit('permission/SET_DEPTINSTITUTIONID', res.profile.inst_id)
          }
        }
        store.commit('permission/SET_FIRSTENTER', false)
      }
      if(to.query?.just_look == 'true'){
        
        if(to.query?.token){
          //token方式
          const arr = to.query?.token.split(' ')
          let token = {
            "access_token": arr[1],
            "token_type": arr[0],
          }

          let info = JSON.stringify(token)
        store.commit('user/SET_LOGININFO', info)
        let res =  await getUserInfo()
        token.profile =  {
          prm_groups:res?.data?.permission_groups?.join(','),
          inst_id:res?.data?.institution_id,
          // permission_groups:
        }
        //userInfo.data
        console.log('收到token了11',token );

        info = JSON.stringify(token)
        store.commit('user/SET_LOGININFO', info)

        }else{
          //oidc方式
        }
        // store.commit('app/SET_IMGSHARE',true)
        // //影像中心---直接放行
        // next()
      }



        await store.dispatch('permission/getPermissions')
      
      if(store.getters.group === 'tenancy' && to.query.group === 'tenancy') { // 从客户跳过来
        store.commit('permission/SET_GROUP', 'tenancy')
      }else if(store.getters.group === '' && to.query.group === 'tenancy') {
        store.commit('permission/SET_GROUP', 'tenancy')
      }else if(store.getters.group === 'tenancy' && to.query.group === 'dept') {
        store.commit('permission/SET_GROUP', 'dept')
      }else if(store.getters.group === '' && to.query.group === 'dept') { // 从科室跳过来
        store.commit('permission/SET_GROUP', 'dept')
      }else if(store.getters.group === 'tenancy' && to.query.group === 'doct') {
        store.commit('permission/SET_GROUP', 'doct')
      }else if(store.getters.group === '' && to.query.group === 'doct') { // 从医生跳过来
        store.commit('permission/SET_GROUP', 'doct')
      } else {
        if(store.getters.group ===  '' || store.getters.group === undefined){
          // console.log('group-here-error',store.getters.group);

          store.commit('permission/SET_GROUP', to.query.group)
        }
        

      }
      // console.log('group异常',store.getters.group);

      // if(store.getters.permissions.length === 0) {
      // }
      if(process.env.NODE_ENV !== 'development') {
        const currentSystemPath = [
          '/paservice/',
          '/paservice/IMGLIST',
          '/paservice/IMGLIST/',
          '/paservice/IMGPROOFREAD',
          '/paservice/IMGPROOFREAD/',
          '/paservice/ROUTELIST',
          '/paservice/ROUTELIST/',
          '/paservice/paramsSetting/bacisParams',
          '/paservice/paramsSetting/frontEndProcessorConfig',
          '/paservice/paramsSetting/imgDeviceConfig',
          '/paservice/paramsSetting/memoryDeviceConfig',
          '/paservice/paramsSetting/routingStrategyConfig',
          '/paservice/paramsSetting/logViewer',
          '/paservice/IMGLIST/matching',
          '/paservice/IMGLIST/splitting',
          '/paservice/IMGLIST/recyclebin',
          '/paservice/error'
        ]
        if(!currentSystemPath.includes(to.path)) { // 不是本系统的路径,open打开
          window.open(configUrl.frontEndUrl + to.path, '_blank')
        }else { // 本系统的路径,先判断是否拥有权限
          if(store.getters.group === 'tenancy') { // 客户管理员(最高权限)
            next()
          }else {
            let authPageMapping = { // 页面权限
              kscdsy: '',
              ksyxlb: 'IMGLIST',
              yxcxly: 'ROUTELIST',
              ksyxjd: 'IMGPROOFREAD',
              kscdsz: 'paramsSetting'
            }
            let currentPathAuth = Object.keys(authPageMapping).filter((ele) => {
              if (authPageMapping[ele] === to.path.split('/')[2]) { // 访问的是本系统的页面
                return ele
              }
            })[0]
            if(store.getters.permissions.includes(currentPathAuth)) { // 拥有权限
              next()
            }else {
              Message({
                message: 'no permission',
                type: 'error',
                duration: 2 * 1000
              })
            }
          }
        }
      }else {
        next()
      }
    }
  })

  return router
}

export { setRouterConfig }
